package com.ruoyi.comparison.controller;

import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.comparison.domain.DataJudgeDetail;
import com.ruoyi.comparison.domain.DataResult;
import com.ruoyi.comparison.domain.TaskJudge;
import com.ruoyi.comparison.domain.TaskJudgeDetail;
import com.ruoyi.comparison.domain.bo.TaskJudgeBo;
import com.ruoyi.comparison.domain.bo.TaskJudgeDetailBo;
import com.ruoyi.comparison.domain.vo.TaskJudgeDetailVo;
import com.ruoyi.comparison.domain.vo.TaskJudgeVo;
import com.ruoyi.comparison.service.ITaskJudgeDetailService;
import com.ruoyi.comparison.service.ITaskJudgeService;
import com.ruoyi.comparison.utils.HttpHelper;
import com.ruoyi.comparison.utils.QiChaChaUtil;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.HttpHead;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 裁判文书信息
 *
 * @author ruoyi
 * @date 2023-11-17
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/judge")
public class TaskJudgeController extends BaseController {

    private final ITaskJudgeService iTaskJudgeService;
    private final ITaskJudgeDetailService iTaskJudgeDetailService;
    @Value("${qichacha.key}")
    private String key;
    @Value("${qichacha.secretKey}")
    private String secretKey;

    //裁判文书
    @SaCheckPermission("system:act:list")
    @GetMapping("/getList")
    public R getList(@RequestParam("searchName") String searchName) {
        if (ObjectUtil.isEmpty(searchName)||searchName.equals("undefined")){
            return null;
        }
        String reqInterNme = "https://api.qichacha.com/JudgmentDocCheck/GetList";
        try {
            HttpHead reqHeader = new HttpHead();
            String[] autherHeader = QiChaChaUtil.RandomAuthentHeader(key, secretKey);
            reqHeader.setHeader("Token", autherHeader[0]);
            reqHeader.setHeader("Timespan", autherHeader[1]);
            String reqUri = reqInterNme.concat("?key=").concat(key).concat("&").concat("searchKey=").concat(searchName);
            String tokenJson = HttpHelper.httpGet(reqUri, reqHeader.getAllHeaders());
            // 解析JSON字符串
            JSONObject jsonObject = new JSONObject(tokenJson);
            String status = jsonObject.getString("Status");
            if (ObjectUtil.isEmpty(tokenJson)){
               throw new EmptyStackException();
            }
            if(status.equals("200")){
                JSONObject result1 = jsonObject.getJSONObject("Result");
                JSONArray data = result1.getJSONArray("Data");
                List<DataResult> dataResults = com.alibaba.fastjson.JSONArray.parseArray(data.toString(), DataResult.class);
                List<DataResult> collect = dataResults.stream().peek(dataResult -> dataResult.setId(null)).collect(Collectors.toList());
                List<TaskJudge> taskJudges = BeanCopyUtils.copyList(collect, TaskJudge.class);
                if (ObjectUtil.isEmpty(taskJudges))
                    return R.ok("无行贿行为");
                List<TaskJudge> list = new ArrayList<>();
                for (int i = 0; i < taskJudges.size(); i++) {
                    TaskJudge taskJudge = taskJudges.get(i);
                    taskJudge.setSearchKey(searchName);
                    iTaskJudgeService.insertOne(taskJudge);
                    list.add(taskJudge);
                    List<TaskJudgeDetail> taskJudgeDetails = BeanCopyUtils.copyList(collect.get(i).getPartyList(), TaskJudgeDetail.class);
                    for (TaskJudgeDetail taskJudgeDetail : taskJudgeDetails) {
                        taskJudgeDetail.setJudgeId(taskJudge.getId());
                    }
                    iTaskJudgeDetailService.insertBatch(taskJudgeDetails);
                }
                return R.ok(list);
            }else {
                return R.ok("查询无结果");
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            return R.fail("裁判文书查询失败！");
        }
    }

    /**
     * 查询裁判文书信息列表
     */
    @SaCheckPermission("system:act:list")
    @GetMapping("/list")
    public TableDataInfo<TaskJudgeVo> list(TaskJudgeBo bo, PageQuery pageQuery) {
        return iTaskJudgeService.queryPageList(bo, pageQuery);
    }

    /**
     * 获取当事人信息，关联裁判文书信息详细信息
     */
    @SaCheckPermission("system:act:list")
    @GetMapping("/detail")
    public TableDataInfo<TaskJudgeDetailVo> findByJudgeId(TaskJudgeDetailBo bo, PageQuery pageQuery) {
        return iTaskJudgeDetailService.queryPageList(bo,pageQuery);
    }
    /**
     * 导出裁判文书信息列表
     */
    @SaCheckPermission("system:act:list")
    @Log(title = "裁判文书信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TaskJudgeBo bo, HttpServletResponse response) {
        List<TaskJudgeVo> list = iTaskJudgeService.queryList(bo);
        ExcelUtil.exportExcel(list, "裁判文书信息", TaskJudgeVo.class, response);
    }

    /**
     * 获取裁判文书信息详细信息
     */
    @SaCheckPermission("system:act:list")
    @GetMapping("/getOne")
    public TableDataInfo<TaskJudgeVo> getInfo(TaskJudgeBo bo,PageQuery pageQuery) {
        if (ObjectUtil.isEmpty(bo)){
            return null;
        }
        return iTaskJudgeService.searchPageList(bo, pageQuery);
    }

    /**
     * 删除裁判文书信息
     *
     * @param ids 主键串
     */
    @SaCheckPermission("system:act:list")
    @Log(title = "裁判文书信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iTaskJudgeService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
